package com.sq.universe.base.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import  com.sq.universe.base.controller.BaseController;
import  com.sq.universe.base.entity.RespEntity;
import  com.sq.universe.base.entity.LogEntity;
import  com.sq.universe.base.service.LogService;
import com.sq.universe.system.entity.FileEntity;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/base/log")
@CrossOrigin
public class LogController extends BaseController {

    @Autowired
    private LogService logService;




    /**
     * 查找日志文件
     * @param
     * @return
     */
    @PostMapping("/getLogs")
//    @RequiresPermissions("base:log:getLogs")
    public RespEntity getLogs(@RequestBody Map data){
        try {
            return logService.getLogs(JSONUtil.parseObj(JSONUtil.toJsonStr(data)));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
     * 关键字筛选
     * @param data
     * @return
     */
    @PostMapping("/readByFilter")
    public RespEntity readByFilter(@RequestBody Map data){
        try {
            return logService.readByFilter(JSONUtil.parseObj(JSONUtil.toJsonStr(data)));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
     * 读取行数
     * @param data
     * @return
     */
    @PostMapping("/readAllLines")
    public RespEntity readAllLines(@RequestBody Map data){
        try {
            return logService.readAllLines(JSONUtil.parseObj(JSONUtil.toJsonStr(data)));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }


    /**
     * 监听模式
     * @param data
     * @return
     */
    @PostMapping("/readByListen")
    public RespEntity readByListen(@RequestBody Map data){
        try {
            return logService.readByListen(JSONUtil.parseObj(JSONUtil.toJsonStr(data)));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
     * 简单模式查看
     * @param data
     * @return
     */
    @PostMapping("/readBySimple")
    public RespEntity readBySimple(@RequestBody Map data){
        try {
            return logService.readBySimple(JSONUtil.parseObj(JSONUtil.toJsonStr(data)));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }


    /**
     * 下载日志文件
     * @param fileName
     * @param response
     */
    @RequestMapping("/download")
    public void download(String  fileName, HttpServletResponse response) {
        String filePath = logService.getFile(fileName);
        try {
            File file = new File(filePath) ;
            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            response.setHeader("Access-Control-Allow-Origin", "*");
            outputStream.write(FileUtil.readBytes(file));
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
    * 查询数据
    * @param logEntity
    * @return
    */
    @PostMapping("/query")
    @RequiresPermissions("base:log:query")
    public RespEntity query(LogEntity logEntity){
        try {
            return new RespEntity("查询成功",logService.query(logEntity));
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
    * 分页查询
    * @param logEntity
    * @return
    */
    @PostMapping("/queryByPage")
    @RequiresPermissions("base:log:queryByPage")

    public RespEntity queryByPage(LogEntity logEntity){
        try {
            PageHelper.startPage(logEntity.getPageNo(),logEntity.getPageSize());
            List<LogEntity> logList = logService.query(logEntity);
            PageInfo<LogEntity> pageInfo = new PageInfo<LogEntity>(logList);
            return new RespEntity("查询成功",pageInfo);
        }catch (Exception exception){
            return new RespEntity("查询失败");
        }
    }

    /**
    * 插入
    * @param logEntity
    * @return
    */
    @PostMapping("/insert")
    @RequiresPermissions("base:log:insert")
    public RespEntity insert(LogEntity logEntity){
        try {
            logService.insert(logEntity);
            return new RespEntity("保存成功");
        }catch (Exception exception){
            return new RespEntity("保存失败");
        }
    }

    /**
    * 更新
    * @param logEntity
    * @return
    */
    @PostMapping("/update")
    @RequiresPermissions("base:log:update")
    public RespEntity update(LogEntity logEntity){
        try {
            logService.update(logEntity);
            return new RespEntity("更新成功");
        }catch (Exception exception){
            return new RespEntity("更新失败");
        }
    }

    /**
    * 删除成功
    * @param logEntity
    * @return
    */
    @PostMapping("/delete")
    @RequiresPermissions("base:log:delete")
    public RespEntity delete(LogEntity logEntity){
        try {
            if(logEntity.getLogId() == null){
                return new RespEntity("删除失败");
            }
            logService.logicalDelete(logEntity);
            return new RespEntity("删除成功");
        }catch (Exception exception){
            return new RespEntity("删除失败");
        }
    }
}